package com.sjw;

import com.sjw.workflow.core.WorkflowContext;
import com.sjw.workflow.dag.WorkflowDAG;
import com.sjw.workflow.dag.WorkflowNode;
import com.sjw.workflow.dag.LogicalExpression;
import com.sjw.workflow.agent.DataProcessingAgent;
import com.sjw.workflow.agent.ValidationAgent;
import com.sjw.workflow.agent.ReportGenerationAgent;
import com.sjw.workflow.engine.WorkflowEngine;
import com.sjw.workflow.engine.WorkflowExecutionResult;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;

/**
 * 简化的测试类
 * 用于测试Workflow管理系统的基本功能
 */
public class SimpleTest {
    
    public static void main(String[] args) {
        System.out.println("=== Workflow Management System Test ===");
        
        try {
            // 创建测试实例
            SimpleTest test = new SimpleTest();
            
            // 运行测试
            test.runTest();
            
            System.out.println("=== Test Completed Successfully ===");
            
        } catch (Exception e) {
            System.err.println("Test failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    public void runTest() throws Exception {
        System.out.println("1. Creating workflow DAG...");
        
        // 创建DAG
        WorkflowDAG dag = new WorkflowDAG("test-workflow");
        
        // 创建Agent
        DataProcessingAgent agent1 = new DataProcessingAgent();
        ValidationAgent agent2 = new ValidationAgent();
        ReportGenerationAgent agent3 = new ReportGenerationAgent();
        
        // 创建节点 - 使用Agent的ID作为节点ID
        WorkflowNode node1 = new WorkflowNode("data-processor", "Data Processing Node", agent1);
        WorkflowNode node2 = new WorkflowNode("validator", "Validation Node", agent2);
        
        // Agent3需要等待Agent1和Agent2都完成
        LogicalExpression condition = LogicalExpression.and(
            LogicalExpression.agentSuccessful("data-processor"),
            LogicalExpression.agentSuccessful("validator")
        );
        WorkflowNode node3 = new WorkflowNode("report-generator", "Report Generation Node", agent3, condition);
        
        // 添加节点到DAG
        dag.addNode(node1);
        dag.addNode(node2);
        dag.addNode(node3);
        
        // 添加依赖关系
        dag.addEdge("data-processor", "report-generator");
        dag.addEdge("validator", "report-generator");
        
        System.out.println("   DAG created with " + dag.size() + " nodes");
        
        // 创建上下文
        System.out.println("2. Setting up workflow context...");
        WorkflowContext context = new WorkflowContext("test-workflow");
        
        // 设置测试数据
        String testData = "Hello World! This is a test message for processing.";
        List<String> testList = Arrays.asList("item1", "item2", "item3");
        
        context.setGlobalData("testText", testData);
        context.setGlobalData("testList", testList);
        
        // 为Agent设置输入数据 - 使用正确的键名
        Map<String, Object> agent1Input = new HashMap<>();
        agent1Input.put("data", testData);
        context.setGlobalData("data-processor_input", agent1Input);
        
        Map<String, Object> agent2Input = new HashMap<>();
        agent2Input.put("data", testList);
        context.setGlobalData("validator_input", agent2Input);
        
        System.out.println("   Test data configured");
        
        // 创建执行引擎
        System.out.println("3. Creating workflow engine...");
        WorkflowEngine engine = new WorkflowEngine();
        
        try {
            // 执行工作流
            System.out.println("4. Executing workflow...");
            CompletableFuture<WorkflowExecutionResult> future = engine.execute(dag, context);
            WorkflowExecutionResult result = future.get();
            
            // 输出结果
            System.out.println("5. Workflow execution completed!");
            printResults(result);
            
        } finally {
            engine.shutdown();
        }
    }
    
    private void printResults(WorkflowExecutionResult result) {
        System.out.println("\n--- Execution Results ---");
        System.out.println("Workflow ID: " + result.getWorkflowId());
        System.out.println("Execution Time: " + result.getExecutionTime() + " ms");
        System.out.println("Total Nodes: " + result.getTotalNodes());
        System.out.println("Completed Nodes: " + result.getCompletedNodes());
        System.out.println("Failed Nodes: " + result.getFailedNodes());
        System.out.println("Success Rate: " + 
            (result.getTotalNodes() > 0 ? (double) result.getCompletedNodes() / result.getTotalNodes() * 100 : 0) + "%");
        
        System.out.println("Overall Status: " + 
            (result.isSuccess() ? "SUCCESS" : result.isPartialSuccess() ? "PARTIAL SUCCESS" : "FAILURE"));
        
        if (result.getError() != null) {
            System.out.println("Error: " + result.getError());
        }
        
        // 打印执行日志
        System.out.println("\n--- Execution Log ---");
        List<String> logs = result.getContext().getExecutionLog();
        for (String log : logs) {
            System.out.println(log);
        }
        
        // 打印Agent结果摘要
        System.out.println("\n--- Agent Results ---");
        Map<String, com.sjw.workflow.core.AgentResult> agentResults = result.getContext().getAllAgentResults();
        for (Map.Entry<String, com.sjw.workflow.core.AgentResult> entry : agentResults.entrySet()) {
            String agentId = entry.getKey();
            com.sjw.workflow.core.AgentResult agentResult = entry.getValue();
            System.out.println("Agent " + agentId + ": " + agentResult.getStatus() + 
                " (execution time: " + agentResult.getExecutionTime() + " ms)");
        }
    }
}
